package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVo;
import com.sky.vo.OrderVo;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocket;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Override
    public OrderSubmitVo submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断地址簿中是否有这个地址
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.selectById(addressBookId);
        if(addressBook==null)
        {
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        Long userId = addressBook.getUserId();
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list==null||list.size()==0)
        {
            throw  new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
     //插入订单表
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(userId);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
       orders.setPayStatus(Orders.UN_PAID);

        orderMapper.insert(orders);
        //插入订单明细表
        List<OrderDetail> orderDetails=new ArrayList<>();
        for (ShoppingCart shoppingCart1 : list) {
               OrderDetail orderDetail=new OrderDetail();
               BeanUtils.copyProperties(shoppingCart1,orderDetail);
               orderDetail.setOrderId(orders.getId());
               orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //返回给前端
        OrderSubmitVo orderSubmitVo=new OrderSubmitVo();
        orderSubmitVo.setId(orders.getId());
        orderSubmitVo.setOrderTime(orders.getOrderTime());
        orderSubmitVo.setOrderNumber(orders.getNumber());
        orderSubmitVo.setOrderAmount(orders.getAmount());
        return orderSubmitVo;

    }

    @Override
    public PageResult historyOrdrers(Integer pageSize, Integer page, Integer status) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
      Page<Orders> page1= orderMapper.getOrders(ordersPageQueryDTO);
      List<OrderVo> orderVoList= new ArrayList<>();
       if(page1!=null&&page1.getTotal()>0)
       {
           for (Orders orders : page1) {
               Long id = orders.getId();
               List<OrderDetail> orderDetails = orderDetailMapper.getById(id);
               OrderVo orderVo=new OrderVo();
               BeanUtils.copyProperties(orders,orderVo);
               orderVo.setOrderDetailList(orderDetails);
               orderVoList.add(orderVo);
           }
       }

        return new PageResult(page1.getTotal(),orderVoList);

    }

    @Override
    public OrderVo getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(orders.getId());
        OrderVo orderVo=new OrderVo();
        BeanUtils.copyProperties(orders,orderVo);
       orderVo.setOrderDetailList(orderDetailList);
        return orderVo;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = orderMapper.getById(id);
        if(orders==null)
        {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Integer status = orders.getStatus();
        if (status > 2) {
            // 只有未支付和待派送的订单可以取消
            throw new AddressBookBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1=new Orders();
        orders1.setId(orders.getId());
        if (status == 2)
        {
            //已经待下单说明还需要退款
            //改变状态
            orders1.setPayStatus(Orders.REFUND);
        }
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelTime(LocalDateTime.now());
        orders1.setCancelReason("用户取消");
        orderMapper.update(orders1);

    }

    @Override
    public void repetition(Long id) {
        Long currentId = BaseContext.getCurrentId();
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(v -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(currentId);
            BeanUtils.copyProperties(v, shoppingCart, "id");
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    @Override
    public void reminder(Long id) {
        //根据id查询订单
Orders orders = orderMapper.getById(id);
          //检验订单是否存在
        if(orders==null)
        {
      throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号：" + orders.getNumber());


        webSocket.sendToAllClient(JSON.toJSONString(map));

    }
}
//